package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @ClassName OrderController
 * @Description TODO
 * @Author zxl
 * @Date 2020/11/19 15:21
 * @Version 1.0
 */
@RestController
@RequestMapping("consumer/order")
@Slf4j
public class OrderController {

    @Resource
    private RestTemplate restTemplate;

    // 使用自己的轮询算法
    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    // 单机版
    // public static final String PAYMENT_URL = "http://localhost:8001";

    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    /**
     * 使用 postForObject 新增数据
     * @param payment
     * @return
     */
    @GetMapping("/create")
    public CommonResult<Payment> create(Payment payment) {
        log.info("接受到的数据：" + payment.getSerial());
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    /**
     * 使用 postForObject 新增数据
     * @param payment
     * @return
     */
    @GetMapping("/createForEntity")
    public CommonResult<Payment> createForEntity(Payment payment) {
        log.info("接受到的数据：" + payment.getSerial());
        ResponseEntity<CommonResult> entity = restTemplate.postForEntity(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
        if ( entity.getStatusCode().is2xxSuccessful() ) {
            return entity.getBody();
        } else {
            return new CommonResult<Payment>(400,"操作失败",null);
        }
    }

    /**
     * 使用 getForObject 查询数据
     * @param id
     * @return
     */
    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById (@PathVariable("id") String id){
        return restTemplate.getForObject(PAYMENT_URL + "/payment/getPaymentById/" + id, CommonResult.class);
    }

    /**
     * 使用 getForEntity 查询数据
     * @param id
     * @return
     */
    @GetMapping("/payment/getForEntity/{id}")
    public CommonResult<Payment> getPaymentByIdForEntity (@PathVariable("id") String id){
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/getPaymentById/" + id, CommonResult.class);
        if ( entity.getStatusCode().is2xxSuccessful() ) {
            return entity.getBody();
        } else {
            return new CommonResult<Payment>(444,"操作失败",null);
        }
    }

    /**
     * 使用自定义轮询算法
     * @return
     */
    @GetMapping("/payment/lb")
    public String getPaymentLB(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if ( instances == null || instances.size() <= 0 ) { // 没有服务的情况
            return null;
        } else {
            for ( int i = 0 ; i < instances.size() ; i ++ ) {
                System.out.println("当前循环服务下标："+i+"，当前服务名称："+instances.get(i).getUri());
            }
        }

        // 调用自定义轮询算法
        ServiceInstance serviceInstance = loadBalancer.instances(instances); // 根据轮询算法得到对应的微服务
        URI uri = serviceInstance.getUri(); // 得到我们的访问地址
        System.out.println("当前uri："+uri.toString());
        return restTemplate.getForObject(uri+"/payment/lb", String.class);
    }

    /**
     * 测试连接zipkin
     * @return
     */
    @GetMapping("/payment/getZipkin")
    public String getPaymentZipKin (){
        String result = restTemplate.getForObject(PAYMENT_URL + "/payment/zipkin" , String.class);
        return result;

        // return restTemplate.getForObject(PAYMENT_URL + "/payment/getPaymentById/" + id, CommonResult.class);
    }

}
